package com.lujianfei.waterpower.ui.power.powerAdd;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.lujianfei.waterpower.ui.power.PowerEntity;
import com.lujianfei.waterpower.utils.BasisTimesUtils;
import com.lujianfei.waterpower.utils.CameraAlbum.ImagePicker;
import com.lujianfei.waterpower.utils.SystemUtils;
import com.lujianfei.waterpower.utils.ToastUtils;

import java.io.File;
import java.util.Calendar;

public class PowerAddPresenter implements PowerAddContract.Presenter {

    PowerAddContract.View view;
    PowerAddContract.Model model;
    PowerEntity powerEntity;
    public PowerAddPresenter(PowerAddContract.View view) {
        this.view = view;
        this.model = new PowerAddModel();
    }

    @Override
    public boolean save() {
        if (view.getUnitPrice()<=0){
            ToastUtils.show("单价不能 <0 或 =0");
            return false;
        }
        if (powerEntity.getSet_date() == 0 ){
            ToastUtils.show("请先选择日期");
            return false;
        }

        powerEntity.setReadout(view.getReadOut());
        powerEntity.setUnit_price(view.getUnitPrice());
        powerEntity.setRemark(view.getRemark());
        powerEntity.save();
        return true;
    }

    @Override
    public void loadData() {
        long id = view.getId();
        if (null == powerEntity && -1!=id) {
            powerEntity = PowerEntity.findById(PowerEntity.class, id);
        }
        if (null == powerEntity){
            powerEntity = new PowerEntity();
        }
        updatePhoto();
        view.setReadOut(""+(int)powerEntity.getReadout());
        view.setUnitPrice(""+powerEntity.getUnit_price());
        view.setRemark(""+powerEntity.getRemark());
        updateDate();
    }

    private void updatePhoto() {
        if (!TextUtils.isEmpty(powerEntity.getUri_photo())) {
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(view.getContext().getContentResolver(),Uri.parse(powerEntity.getUri_photo()));
                view.setBitmap(bitmap);
                view.showDelete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            view.setImageDefault();
            view.hideDelete();
        }
    }

    private void updateDate() {
        view.setDate(TextUtils.isEmpty(powerEntity.getDateStr())?"请选择日期":powerEntity.getDateStr());
    }

    @Override
    public void openDatePicker() {
        Calendar instance = Calendar.getInstance();
        if ( 0!=powerEntity.getSet_date() ) {
            instance.setTimeInMillis(powerEntity.getSet_date());
        }
        BasisTimesUtils.showDatePickerDialog(view.getContext(), false, "请选择年月日", instance.get(Calendar.YEAR), instance.get(Calendar.MONTH)+1, instance.get(Calendar.DAY_OF_MONTH), new BasisTimesUtils.OnDatePickerListener() {
            @Override
            public void onConfirm(int year, int month, int dayOfMonth) {
                Calendar instance = Calendar.getInstance();
                instance.set(year, month - 1, dayOfMonth,0,0,0);
                long timeInMillis = instance.getTimeInMillis();
                powerEntity.setReadout(view.getReadOut());
                powerEntity.setUnit_price(view.getUnitPrice());
                powerEntity.setSet_date(timeInMillis);
                updateDate();
            }

            @Override
            public void onCancel() {

            }
        });
    }

    @Override
    public void openImagePicker() {
        model.requestOpenAlbumPermissions(view.getContext());
        new ImagePicker.Builder((Activity)view.getContext())
                .openAlbum();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK){
            return;
        }
        File outputFile = new File(SystemUtils.getApplicationContext().getFilesDir(),""+System.currentTimeMillis()+".jpg");
        switch (requestCode){
            case ImagePicker.REQUEST_CODE_ALBUM:{
                //相册选择图片完毕，进行图片裁切
                Uri uri = data.getData();
                if (data == null ||  uri ==null) {
                    return;
                }
                try {
                    powerEntity.setUri_photo(uri.toString());
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(view.getContext().getContentResolver(),uri);
                    view.setBitmap(bitmap);
                    updatePhoto();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            break;
            case ImagePicker.REQUEST_CODE_CAMERA:{

            }
            break;
            case ImagePicker.REQUEST_CODE_CROP:{
                try {
                    Uri uri = Uri.fromFile(outputFile);
                    Bitmap bitmap = BitmapFactory.decodeStream(view.getContext().getContentResolver().openInputStream(uri));
                    view.setBitmap(bitmap);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
            break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    }

    @Override
    public void removePhoto() {
        powerEntity.setUri_photo("");
        updatePhoto();
    }
}
